package security.Authentication.Base;

/**
 * Head of an authentication handler chain
 * @author Andreas Carmvall
 */
public class AuthenticationChain extends AuthenticationHandler {

	/**
	 * The last handler in the chain
	 */
	private AuthenticationHandler lastHandler = null;

	/**
	 * Add handler to the last handler in the chain
	 */
	@Override
	public void setNext(AuthenticationHandler handler) {
		if (lastHandler != null) {
			lastHandler.setNext(handler);
		} else {
			next = handler;
		}
		
		lastHandler = handler;
	}

	@Override
	public User handleRequest(AuthenticationRequest request) {
		if (next != null) {
			return next.handleRequest(request);
		} else {
			return new UnknownUser("Empty chain", false);
		}
	}
	
	/**
	 * Clear the chain
	 */
	public void clear() {
		lastHandler = null;
		next = null;
	}
}
